﻿using System;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Dapper.Contrib.Extensions;
using Newtonsoft.Json.Linq;
using pinduoduo.Model;
using pinduoduo.Util;
using RestSharp;
using RestSharp.Extensions;
using Sunny.UI;
using Tk.Soc.Share.Common.Helpers;

namespace pinduoduo.Page
{
    public partial class CommentForm : UIPage
    {
      

        public CommentForm( )
        {
            InitializeComponent();

            string  path = AppDomain.CurrentDomain.BaseDirectory + "好评.txt";
            if (File.Exists(path)) 
            {
                this.comment.Text = File.ReadAllText(path);
            }
         
        }

   
        private void comment_TextChanged(object sender, EventArgs e)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "好评.txt";
            File.WriteAllText(path, this.comment.Text);
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {

        }

        private async void uiButton1_Click_1(object sender, EventArgs e)
        {
            string goodId = "";
            UIInputDialog.InputStringDialog(ref goodId, true, "请输入采集ID");

            if (string.IsNullOrWhiteSpace(goodId))
            {
                ShowErrorNotifier("请输入采集ID再操作");
                return;
            }

            var res = await PddApi.GetGoodsComments(goodId,"");
            if (res.StatusCode != System.Net.HttpStatusCode.OK) 
            {
                ShowErrorNotifier("采集失败");
                return;
            }

            this.comment.Text = "";

            string path = AppDomain.CurrentDomain.BaseDirectory + "订单好评";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            path = AppDomain.CurrentDomain.BaseDirectory + "订单好评\\" + goodId;
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            try
            {
                Regex reg = new Regex("window.rawData=(?<key2>.*?)};");
                Match match = reg.Match(res.Content);
                string tempStr = match.Groups["key2"].Value;
                if (string.IsNullOrWhiteSpace(tempStr))
                {
                    LogHelper.Logger.Debug("解析数据失败：" + res.Content);
                    ShowErrorNotifier("解析数据失败");
                    return;
                }

                var jo = JObject.Parse(tempStr + " }");

                var commentsList = jo["store"]["commentsList"].ToArray();
                int index = 1;
                foreach (var comments in commentsList)
                {
                    string orderPath = path + "\\" + index;
                    if (!Directory.Exists(orderPath))
                    {
                        Directory.CreateDirectory(orderPath);
                    }
                    Msg("采集到："+ index +"条评论");
                    var comment = comments["comment"].ToString();
                    var picAndVideos = comments["picAndVideo"].ToArray();
                    foreach (var picAndVideo in picAndVideos)
                    {
                        var url =  picAndVideo["url"].ToString();
                        if (url.EndsWith(".jpeg")) 
                        {
                            var restclient = new RestClient(url);
                            Msg("采集到评论图片：" + url);
                            restclient.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36";
                            restclient.Timeout = 5000;
                            var request = new RestRequest(Method.GET);
                            var bytes = restclient.DownloadData(request);
                            MemoryStream memoryStream = new MemoryStream(bytes);
                            var uuidN = Guid.NewGuid().ToString("N");
                            FileStream fileStream = new FileStream(path +"\\"+ index+"\\"+ uuidN + ".jpg",FileMode.OpenOrCreate);
                            memoryStream.WriteTo(fileStream);
                            memoryStream.Close();
                            fileStream.Close();
                        }
                    

                    }
                    index++;
                    this.comment.AppendText(comment + "\r\n");
                }
                ShowSuccessNotifier("采集成功");
            }
            catch (Exception e1)
            {
                LogHelper.Logger.Debug("解析数据失败", e1);
                ShowSuccessNotifier("采集错误");
            }
         
    

        }

        private void Msg(string msg, bool error = false, bool enter = true)
        {
            if (error) this.LogRichTextBox.SelectionColor = Color.Red;

            LogRichTextBox.AppendText(msg);

            if (enter) LogRichTextBox.AppendText("\r\n");

            if (error) this.LogRichTextBox.SelectionColor = Color.Black;
        }
    }
}
